package com.five.admin.controller;

import com.five.admin.server.MenuService;
import com.five.admin.vo.MenuTreeVo;
import com.five.core.result.Result;
import com.five.core.result.ResultEnum;
import com.five.pojo.dto.BatchIds;
import com.five.pojo.entity.Menu;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Resource
    private MenuService menuService;

    @RequestMapping(value = "/treeMenu", method = RequestMethod.GET)
    public Result treeMenu(){
        List<MenuTreeVo> menuTree = menuService.getMenuTree();
        return Result.buildSuccess(menuTree);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@RequestBody Menu menu){
        System.out.println("menu = " + menu);
        if (menuService.save(menu)) {
            return Result.buildSuccess();
        }
        return Result.buildFail(ResultEnum.ADD_FALSE);
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public Result update(@RequestBody Menu menu){
        System.out.println("menu = " + menu);
        if (menuService.updateById(menu)) {
            return Result.buildSuccess();
        }
        return Result.buildFail(ResultEnum.UPDATE_FALSE);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable("id") Long id){
        menuService.deleteRoleMenu(id);
        if (menuService.removeById(id)) {
            return Result.buildSuccess();
        }
        return Result.buildFail(ResultEnum.DELETE_FALSE);
    }

    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result deleteBatch(@RequestBody @Valid BatchIds batchIds){
        batchIds.getIds().forEach(id->{
            menuService.deleteRoleMenu(id);
        });
        if (menuService.removeByIds(batchIds.getIds())) {
            return Result.buildSuccess();
        }
        return Result.buildFail(ResultEnum.DELETE_FALSE);
    }
    @RequestMapping(value = "/queryOne/{id}", method = RequestMethod.GET)
    public Result queryOne(@PathVariable("id") Long id){
        Menu menu = menuService.getById(id);
        return Result.buildSuccess(menu);
    }

    @RequestMapping(value = "/getMenu", method = RequestMethod.GET)
    public Result getMenu(){
        return Result.buildSuccess(menuService.getMenuRouter());
    }

    @RequestMapping(value = "/getRoleHasMenu", method = RequestMethod.GET)
    public Result getRoleHasMenu(Long id){
        return Result.buildSuccess(menuService.getRoleHasMenu(id));
    }

    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    public Result getMenuTree(){
        return Result.buildSuccess(menuService.getMenuTree());
    }
}
